package com.erplan.swt.app.gx;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import com.erplan.swt.app.gx.db.DBConnection;
import com.erplan.swt.app.gx.dialogs.GxAbout;

public class GxPopupMenu {

	public static void createPopupMenu() {

		Menu popupMenu = new Menu (Gx.shell, SWT.POP_UP);
		popupMenu.addListener(SWT.Hide, GxStatusBar.hideListener);
		popupMenu.addListener(SWT.Show, GxStatusBar.showListener);

		//Creating Help Menu
		MenuItem popupMenuItem = new MenuItem(popupMenu, SWT.CASCADE);
		popupMenuItem.setText("Help");
		popupMenuItem.addListener(SWT.Arm, GxStatusBar.armListener);
		Menu helpMenu = new Menu(Gx.shell, SWT.DROP_DOWN);
		helpMenu.addListener(SWT.Hide, GxStatusBar.hideListener);
		helpMenu.addListener(SWT.Show, GxStatusBar.showListener);
		popupMenuItem.setMenu(helpMenu);

		popupMenuItem = new MenuItem(helpMenu, SWT.CASCADE);
		popupMenuItem.setText("About " + Gx.toolTextSmall);
		popupMenuItem.addListener(SWT.Arm, GxStatusBar.armListener);
		popupMenuItem.addListener(SWT.Selection, new Listener () {
			public void handleEvent (Event e) {
				GxAbout p5About = new GxAbout();
				Shell aboutDialog = p5About.createAboutDialog(Gx.shell, Gx.display);
				aboutDialog.open();

				while (!aboutDialog.isDisposed ()) {
					if (!Gx.display.readAndDispatch ()) Gx.display.sleep ();
				}
			}
		});

		popupMenuItem = new MenuItem(popupMenu, SWT.SEPARATOR);

		popupMenuItem = new MenuItem(popupMenu, SWT.PUSH);
		popupMenuItem.setText("E&xit\tAlt+X");
		popupMenuItem.setAccelerator (SWT.ALT + 'X');
		popupMenuItem.addListener(SWT.Arm, GxStatusBar.armListener);
		popupMenuItem.addListener(SWT.Selection, new Listener () {
			public void handleEvent (Event e) {
				MessageBox messageBox = new MessageBox (Gx.shell, SWT.APPLICATION_MODAL | SWT.ICON_QUESTION | SWT.YES | SWT.NO);
				messageBox.setText(Gx.toolTextSmall);
				messageBox.setMessage("Close " + Gx.toolTextSmall + " ?");
				if(messageBox.open() == SWT.YES){
					Gx.display.dispose();
					DBConnection.close();
					System.exit(0);
				}
			}
		});

		Gx.shell.setMenu(popupMenu);
		Gx.clientArea.setMenu(popupMenu);
	}
}
